from apps.common.base.dao import BaseDao
from apps.merchant.sku.serializers import *
from django.db.models import F

class SkuDao(BaseDao):
    MODEL_CLASS = Sku
    SERI_CLASS = SkuBaseSerializer

    # 增加库存
    def addStock(self, itemId, n):
        if not n:
            return
        try:
            item = SkuDao().findOneByObjId(itemId)
            item.stock = F('stock') + n
            item.save()
        except Exception as e:
            print(e)

    # 减少库存
    def subStock(self, itemId, n):
        if not n:
            return
        try:
            item = SkuDao().findOneByObjId(itemId)
            if item.stock > n:
                item.stock = F('stock') - n
            else:
                item.stock = 0
            item.save()
        except Exception as e:
            print(e)

    # 增加销量
    def addSales(self, itemId, n):
        if not n:
            return
        try:
            item = SkuDao().findOneByObjId(itemId)
            item.sales = F('sales') + n
            item.save()
        except Exception as e:
            print(e)

    # 减少销量
    def subSales(self, itemId, n):
        if not n:
            return
        try:
            item = SkuDao().findOneByObjId(itemId)
            item.sales = F('sales') - n
            item.save()
        except Exception as e:
            print(e)